<template>
  <div class="app-container">
    <div class="jiaqitop">
      <div class="titlel">
        <div class="titlel_box"></div>
        <div class="titlel_tt">角色管理</div>
      </div>
      <el-button class="addtj" color="#003779" @click="popubool = true">
        <img src="/src/assets/images/Union@2x.png" alt="" />
        <span style="margin-left: 6px">添加</span>
      </el-button>
    </div>
    <el-card shadow="hover" class="data-table">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="roleList"
        highlight-current-row
        border
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="ID" width="55" prop="id" align="center" />
        <el-table-column label="父级" prop="name" align="center" min-width="705" />
        <el-table-column label="名称" prop="code" align="center" min-width="365" />
        <el-table-column label="状态" align="center" min-width="243">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="排序" align="center" width="80" prop="sort" />

        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              icon="position"
              @click="handleOpenAssignPermDialog(scope.row)"
            >
              分配权限
            </el-button>
            <span style="color: #165dff; cursor: pointer">编辑</span>
            <span style="margin-left: 10px; margin-right: 10px">|</span>
            <span style="color: #f53f3f; cursor: pointer" @click="handleDelete(scope.row.id)">
              删除
            </span>
            <!-- <el-button
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="fetchData"
      />
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="roleFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入角色编码" />
        </el-form-item>

        <el-form-item label="数据权限" prop="dataScope">
          <el-select v-model="formData.dataScope">
            <el-option :key="1" label="全部数据" :value="1" />
            <el-option :key="2" label="部门及子部门数据" :value="2" />
            <el-option :key="3" label="本部门数据" :value="3" />
            <el-option :key="4" label="本人数据" :value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            :min="0"
            style="width: 100px"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配权限弹窗 -->
    <el-drawer
      v-model="assignPermDialogVisible"
      :title="'【' + checkedRole.name + '】权限分配'"
      :size="drawerSize"
    >
      <div class="flex-x-between">
        <el-input v-model="permKeywords" clearable class="w-[150px]" placeholder="菜单权限名称">
          <template #prefix>
            <Search />
          </template>
        </el-input>

        <div class="flex-center ml-5">
          <el-button type="primary" size="small" plain @click="togglePermTree">
            <template #icon>
              <Switch />
            </template>
            {{ isExpanded ? "收缩" : "展开" }}
          </el-button>
          <el-checkbox
            v-model="parentChildLinked"
            class="ml-5"
            @change="handleparentChildLinkedChange"
          >
            父子联动
          </el-checkbox>

          <el-tooltip placement="bottom">
            <template #content>
              如果只需勾选菜单权限，不需要勾选子菜单或者按钮权限，请关闭父子联动
            </template>
            <el-icon class="ml-1 color-[--el-color-primary] inline-block cursor-pointer">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </div>
      </div>

      <el-tree
        ref="permTreeRef"
        node-key="value"
        show-checkbox
        :data="menuPermOptions"
        :filter-node-method="handlePermFilter"
        :default-expand-all="true"
        :check-strictly="!parentChildLinked"
        class="mt-5"
      >
        <template #default="{ data }">
          {{ data.label }}
        </template>
      </el-tree>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleAssignPermSubmit">确 定</el-button>
          <el-button @click="assignPermDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-drawer>
    <el-dialog v-model="popubool" :show-close="false" width="49.0625rem" :modal="false" center>
      <template #header>
        <div class="popubox">
          <div class="backtop">
            <div class="topline">
              <div class="text">新增成员</div>
              <img
                src="/src/assets/images/微信图片_20250903150026_21_215.png"
                @click="popubool = false"
                alt=""
              />
            </div>
          </div>
          <div class="bdan">
            <el-form
              ref="queryFormRef"
              class="form1"
              :model="formData"
              :rules="rules"
              :inline="true"
            >
              <el-form-item label="姓名:" prop="name">
                <el-input v-model="formData.name" placeholder="请输入姓名" />
              </el-form-item>

              <div class="bdan1">
                <div class="title1">角色和权限</div>
                <div class="backnone" style="margin-top: 22px">
                  <el-form-item label="他的权限:" label-width="90">
                    <el-checkbox-group v-model="queryParams.val">
                      <el-checkbox label="选择全部" size="32"></el-checkbox>
                      <el-checkbox label="展开全部" size="32"></el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </div>
                <div class="quxnainlist">
                  <el-tree
                    ref="permTreeRef"
                    node-key="value"
                    show-checkbox
                    :data="menuPermOptions"
                    :filter-node-method="handlePermFilter"
                    :default-expand-all="true"
                    :check-strictly="!parentChildLinked"
                    class="mt-5"
                  >
                    <template #default="{ data }">
                      {{ data.label }}
                    </template>
                  </el-tree>
                </div>

                <div class="backnone">
                  <el-form-item label="状态:" label-width="90">
                    <el-radio-group v-model="queryParams.val" size="small">
                      <el-radio label="1" size="32" border>隐藏</el-radio>
                      <el-radio label="2" size="32" border>显示</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </div>
            </el-form>
            <el-form ref="queryFormRef" :model="formData" :rules="rules" :inline="true"></el-form>
          </div>
          <div class="btnss">
            <el-button @click="handleResetQuery">取消</el-button>
            <el-button type="primary" @click="handleQuery" style="margin-right: 34px">
              确定
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app-store";
import { DeviceEnum } from "@/enums/settings/device.enum";
import { CircleCloseFilled } from "@element-plus/icons-vue";
import RoleAPI, { RolePageVO, RoleForm, RolePageQuery } from "@/api/system/role-api";
import MenuAPI from "@/api/system/menu-api";

defineOptions({
  name: "Role",
  inheritAttrs: false,
});
const options = [
  {
    value: "Option1",
    label: "Option1",
  },
  {
    value: "Option2",
    label: "Option2",
  },
  {
    value: "Option3",
    label: "Option3",
  },
  {
    value: "Option4",
    label: "Option4",
  },
  {
    value: "Option5",
    label: "Option5",
  },
];

const popubool = ref(false);

const appStore = useAppStore();

const queryFormRef = ref();
const roleFormRef = ref();
const permTreeRef = ref();

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<RolePageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 角色表格数据
const roleList = ref<RolePageVO[]>();
// 菜单权限下拉
const menuPermOptions = ref<OptionType[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));

// 角色表单
const formData = reactive<RoleForm>({
  sort: 1,
  status: 1,
});

const rules = reactive({
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入角色编码", trigger: "blur" }],
  dataScope: [{ required: true, message: "请选择数据权限", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
});

// 选中的角色
interface CheckedRole {
  id?: string;
  name?: string;
}
const checkedRole = ref<CheckedRole>({});
const assignPermDialogVisible = ref(false);

const permKeywords = ref("");
const isExpanded = ref(true);

const parentChildLinked = ref(true);

// 获取数据
function fetchData() {
  loading.value = true;
  RoleAPI.getPage(queryParams)
    .then((data) => {
      roleList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

// 行复选框选中
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 打开角色弹窗
function handleOpenDialog(roleId?: string) {
  dialog.visible = true;
  if (roleId) {
    dialog.title = "修改角色";
    RoleAPI.getFormData(roleId).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增角色";
  }
}

// 提交角色表单
function handleSubmit() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.id;
      if (roleId) {
        RoleAPI.update(roleId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        RoleAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;

  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();

  formData.id = undefined;
  formData.sort = 1;
  formData.status = 1;
}

// 删除角色
function handleDelete(roleId?: number) {
  const roleIds = [roleId || ids.value].join(",");
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error",
    icon: markRaw(CircleCloseFilled),
  }).then(
    () => {
      loading.value = true;
      RoleAPI.deleteByIds(roleIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开分配菜单权限弹窗
async function handleOpenAssignPermDialog(row: RolePageVO) {
  const roleId = row.id;
  if (roleId) {
    assignPermDialogVisible.value = true;
    loading.value = true;

    checkedRole.value.id = roleId;
    checkedRole.value.name = row.name;

    // 获取所有的菜单
    menuPermOptions.value = await MenuAPI.getOptions();

    // 回显角色已拥有的菜单
    RoleAPI.getRoleMenuIds(roleId)
      .then((data) => {
        const checkedMenuIds = data;
        checkedMenuIds.forEach((menuId) => permTreeRef.value!.setChecked(menuId, true, false));
      })
      .finally(() => {
        loading.value = false;
      });
  }
}

// 分配菜单权限提交
function handleAssignPermSubmit() {
  const roleId = checkedRole.value.id;
  if (roleId) {
    const checkedMenuIds: number[] = permTreeRef
      .value!.getCheckedNodes(false, true)
      .map((node: any) => node.value);

    loading.value = true;
    RoleAPI.updateRoleMenus(roleId, checkedMenuIds)
      .then(() => {
        ElMessage.success("分配权限成功");
        assignPermDialogVisible.value = false;
        handleResetQuery();
      })
      .finally(() => {
        loading.value = false;
      });
  }
}

// 展开/收缩 菜单权限树
function togglePermTree() {
  isExpanded.value = !isExpanded.value;
  if (permTreeRef.value) {
    Object.values(permTreeRef.value.store.nodesMap).forEach((node: any) => {
      if (isExpanded.value) {
        node.expand();
      } else {
        node.collapse();
      }
    });
  }
}

// 权限筛选
watch(permKeywords, (val) => {
  permTreeRef.value!.filter(val);
});

function handlePermFilter(
  value: string,
  data: {
    [key: string]: any;
  }
) {
  if (!value) return true;
  return data.label.includes(value);
}

// 父子菜单节点是否联动
function handleparentChildLinkedChange(val: any) {
  parentChildLinked.value = val;
}

onMounted(() => {
  handleQuery();
});
</script>
<style lang="scss" scoped>
:v-deep .el-dialog--center {
  padding: 0 !important;
}
.quxnainlist {
  width: 607px;
  background: #f7f8fa;
  overflow: hidden;
  margin-left: 111px;
  border-radius: 14px 14px 14px 14px;
  margin-bottom: 18px;
}
.backnone {
  ::v-deep .el-form-item--default .el-form-item__content {
    background: none !important;
    height: 32px;
  }
}
.backnone1 {
}
::v-deep .el-input__wrapper {
  background: #f7f8fa;
  box-shadow: none !important;
  height: 52px;
}
::v-deep .el-form-item--default .el-form-item__content {
  width: 44.875rem;
  height: 52px;
  background: #f7f8fa;
  box-shadow: none !important;
  border-radius: 6px 6px 6px 6px;
}
::v-deep .el-dialog__header {
  border: none !important;
  padding: 0 !important;
}
.btnss {
  width: 100%;
  display: flex;
  height: 77px;
  background: #ffffff;
  box-shadow: 0px -2px 12px 0px rgba(14, 14, 14, 0.08);
  border-radius: 0px 0px 0px 0px;
  justify-content: flex-end;
  align-items: center;
  .el-button {
    width: 118px;
    height: 41px;
  }
}
::v-deep .el-dialog {
  padding: 0 !important;
}
.popubox {
  width: 100%;
  overflow: hidden;
  .bdan1 {
    width: 44.875rem;
    margin: auto;
    margin-top: 24px;
    border-top: 1px solid #e5e6eb;
    overflow: hidden;
    .title1 {
      font-family:
        PingFang SC,
        PingFang SC;
      font-weight: bold;
      font-size: 20px;
      color: #1d2129;
      margin-top: 21px;
      width: 100%;
      text-align: left;
    }
    ::v-deep .el-form-item {
      display: inline-flex !important;
      align-items: center !important;
    }
    ::v-deep .el-form-item__label {
      margin-bottom: 0 !important;
    }
  }
  .bdan {
    width: 44.875rem;
    margin: auto;
    margin-top: 19px;
    .form1 {
    }
    ::v-deep .el-form-item {
      display: block;
    }
    :v-deep .el-input {
      width: 49.125rem !important;
    }
    ::v-deep .el-radio__input.is-checked .el-radio__inner {
      background: #ffffff !important;
    }
    ::v-deep .el-radio__input.is-checked .el-radio__inner::after {
      background: #003779 !important;
      width: 8px;
      height: 8px;
    }
    ::v-deep .el-form-item__label {
      height: 32px;
      width: 100%;
      line-height: 32px;
      display: block;
      text-align: left !important;
      margin-bottom: 16px;
    }
  }
  .qdbtn {
    width: 113px;
    height: 44px;
    background: #003779;
    border-radius: 6px 6px 6px 6px;
    text-align: center;
    line-height: 44px;
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 400;
    font-size: 15px;
    color: #ffffff;
    margin-left: 789px;
    margin-top: 24px;
  }
  .xzbox {
    width: 87.5rem;
    margin: auto;
    margin-top: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .el-select {
      width: 18.6875rem;
      border-radius: 6px 6px 6px 6px;
      display: flex;
      font-size: 1rem;
      align-items: center;
    }
    .daochubtn {
      width: 7.0625rem;
      height: 2.75rem;
      border: 1px solid #4e5969;
      border-radius: 4px 4px 4px 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 0.9375rem;
      color: #4e5969;
      img {
        width: 1rem;
        height: 1rem;
      }
    }
  }
  .titleboxs {
    width: 87.5rem;
    margin: auto;
    margin-top: 16px;
    height: 60px;
    background: #edf1fc;
    border-radius: 8px 8px 8px 8px;
    display: flex;
    align-items: center;

    .yijibt {
      margin-left: 24px;
      font-family:
        PingFang SC,
        PingFang SC;
      font-weight: bold;
      font-size: 1.125rem;
      color: #003779;
    }
    .fgx {
      width: 1px;
      height: 2.75rem;
      border-radius: 0px 0px 0px 0px;
      background: rgba(0, 55, 121, 0.5);
      margin-left: 4.625rem;
    }
    .erjibt {
      font-family:
        PingFang SC,
        PingFang SC;
      font-weight: bold;
      font-size: 1.125rem;
      color: #003779;
      margin-left: 44px;
    }
  }
  .backtop {
    width: 100%;
    height: 54px;
    background: #e5e6eb;
    display: flex;
    align-items: center;
    .topline {
      width: 44.875rem;

      margin: auto;
      display: flex;
      justify-content: space-between;
      .text {
        font-family:
          PingFang SC,
          PingFang SC;
        font-weight: bold;
        font-size: 18px;
        color: #4e5969;
      }
      img {
        width: 24px;
        height: 24px;
      }
    }
  }
}

.el-card {
  border-radius: 16px 16px 16px 16px;
}
.jiaqitop {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  .addtj {
    width: 7rem;
    height: 2.75rem;

    border-radius: 6px 6px 6px 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 400;
    font-size: 0.9375rem;
    color: #ffffff;
    img {
      width: 0.5625rem;
      height: 0.5625rem;
    }
  }
  .titlel {
    display: flex;
    align-items: center;
    .titlel_box {
      width: 4px;
      height: 23px;
      background: #003779;
      border-radius: 0px 6px 6px 0px;
    }
    .titlel_tt {
      font-family:
        PingFang SC,
        PingFang SC;
      font-weight: bold;
      font-size: 1.375rem;
      color: #1d2129;
      margin-left: 9px;
    }
  }
}
::v-deep .el-tree {
  background: none !important;
}
</style>
